{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "# BNN on Pynq\n",
    "\n",
    "This notebook covers how to use Binary Neural Networks on Pynq. \n",
    "It shows an example of handwritten digit recognition using a binarized neural network composed of 4 fully connected layers with 1024 neurons each, trained on the MNIST dataset of handwritten digits. \n",
    "In order to reproduce this notebook, you will need an external USB Camera connected to the PYNQ Board.\n",
    "\n",
    "## 1.Instantiate the classifier\n",
    "Creating a classifier will automatically download the correct bitstream onto the device and load the weights trained on the specified dataset. By default there is one set of weights for the LFC network, the MNIST"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "import bnn\n",
    "print(bnn.available_params(bnn.NETWORK_LFC))\n",
    "\n",
    "classifier = bnn.PynqBNN(network=bnn.NETWORK_LFC)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "# 2. Download the network parameters\n",
    "The parameters of the network are downloaded in the Programmable logic memory, storing the trained weights on the MNIST dataset. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "classifier.load_parameters(\"chars_merged\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "## 3. Load the image from the camera\n",
    "The image is captured from the external USB camera and stored locally. The image is then enhanced in contract and brightness to remove background noise. \n",
    "The resulting image should show the digit on a white background:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "from PIL import Image as PIL_Image\n",
    "from PIL import ImageEnhance\n",
    "from PIL import ImageOps\n",
    "\n",
    "orig_img_path = '/home/xilinx/image.jpg'\n",
    "!fswebcam  --no-banner --save {orig_img_path} -d /dev/video0 2> /dev/null # Loading the image from the webcam\n",
    "\n",
    "img = PIL_Image.open(orig_img_path).convert(\"L\")                          # convert in black and white  \n",
    "  \n",
    "#Image enhancement                  \n",
    "contr = ImageEnhance.Contrast(img)  \n",
    "img = contr.enhance(3)                                                    # The enhancement values (contrast and brightness)   \n",
    "bright = ImageEnhance.Brightness(img)                                     # depends on backgroud, external lights etc  \n",
    "img = bright.enhance(4.0)            \n",
    "\n",
    "#img = img.rotate(180)                                                     # Rotate the image (depending on camera orientation)  \n",
    "#Adding a border for future cropping  \n",
    "img = ImageOps.expand(img,border=80,fill='white')   \n",
    "threshold = 180    \n",
    "img = img.point(lambda p: p > threshold and 255)   \n",
    "img"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "## 4. Crop and scale the image "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "from PIL import Image as PIL_Image\n",
    "import numpy as np\n",
    "import math\n",
    "from scipy import misc\n",
    "\n",
    "#Find bounding box  \n",
    "inverted = ImageOps.invert(img)  \n",
    "box = inverted.getbbox()  \n",
    "img_new = img.crop(box)  \n",
    "width, height = img_new.size  \n",
    "ratio = min((28./height), (28./width))  \n",
    "background = PIL_Image.new('RGB', (28,28), (255,255,255))  \n",
    "if(height == width):  \n",
    "    img_new = img_new.resize((28,28))  \n",
    "elif(height>width):  \n",
    "    img_new = img_new.resize((int(width*ratio),28))  \n",
    "    background.paste(img_new, (int((28-img_new.size[0])/2),int((28-img_new.size[1])/2)))  \n",
    "else:  \n",
    "    img_new = img_new.resize((28, int(height*ratio)))  \n",
    "    background.paste(img_new, (int((28-img_new.size[0])/2),int((28-img_new.size[1])/2)))  \n",
    "  \n",
    "background  \n",
    "img_data=np.asarray(background)  \n",
    "img_data = img_data[:,:,0]  \n",
    "misc.imsave('/home/xilinx/img_webcam.png', img_data) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "## 5. Convert to BNN input format\n",
    "The image is resized to comply with the MNIST standard. The image is resized at 28x28 pixels and the colors inverted. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "from array import *\n",
    "from PIL import Image as PIL_Image\n",
    "img_load = PIL_Image.open('/home/xilinx/img_webcam.png').convert(\"L\")  \n",
    "# Convert to BNN input format  \n",
    "# The image is resized to comply with the MNIST standard. The image is resized at 28x28 pixels and the colors inverted.   \n",
    "  \n",
    "#Resize the image and invert it (white on black)  \n",
    "smallimg = ImageOps.invert(img_load)  \n",
    "smallimg = smallimg.rotate(0)  \n",
    "  \n",
    "data_image = array('B')  \n",
    "  \n",
    "pixel = smallimg.load()  \n",
    "for x in range(0,28):  \n",
    "    for y in range(0,28):  \n",
    "        if(pixel[y,x] == 255):  \n",
    "            data_image.append(255)  \n",
    "        else:  \n",
    "            data_image.append(1)  \n",
    "          \n",
    "# Setting up the header of the MNIST format file - Required as the hardware is designed for MNIST dataset         \n",
    "hexval = \"{0:#0{1}x}\".format(1,6)  \n",
    "header = array('B')  \n",
    "header.extend([0,0,8,1,0,0])  \n",
    "header.append(int('0x'+hexval[2:][:2],16))  \n",
    "header.append(int('0x'+hexval[2:][2:],16))  \n",
    "header.extend([0,0,0,28,0,0,0,28])  \n",
    "header[3] = 3 # Changing MSB for image data (0x00000803)  \n",
    "data_image = header + data_image  \n",
    "output_file = open('/home/xilinx/image.images-idx3-ubyte', 'wb')  \n",
    "data_image.tofile(output_file)  \n",
    "output_file.close()   \n",
    "smallimg  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "# 6. Launching BNN in hardware\n",
    "The image is passed in the PL and the inference is performed"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true,
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "class_out= classifier.inference(\"/home/xilinx/image.images-idx3-ubyte\")\n",
    "print(\"Class number: {0}\".format(class_out))\n",
    "print(\"Class name: {0}\".format(classifier.class_name(class_out)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "celltoolbar": "Raw Cell Format",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
